package cqrtplm.aop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hustcad.plm.pdm.common.model.vo.BusinessObjectVO;
import com.hustcad.plm.pdm.common.model.vo.iteration.CommonIteratorVO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.dto.RtCfgStatusDTO;
import cqrtplm.entity.RtCfgStatusInfoDO;
import cqrtplm.entity.RtCfgStatusInfodetailDO;
import cqrtplm.mapper.RtCfgStatusInfoMapper;
import cqrtplm.mapper.RtCfgStatusInfodetailMapper;
import cqrtplm.service.DocRevisionService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Aspect
@Component
@Slf4j
public class DocRevisionAop {

    @Resource
    private DocRevisionService docRevisionService;
    @Resource
    private RtCfgStatusInfoMapper rtCfgStatusInfoMapper;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private RtCfgStatusInfodetailMapper rtCfgStatusInfodetailMapper;

    @Around(value = "execution(* com.hustcad.plm.pdm.iteration.controller.TyplmIterationController.batchNewVersionWithPolicy(..))")
    @Transactional(rollbackFor = Exception.class)
    public Object DocRevision(ProceedingJoinPoint point) throws Throwable {

        // 获取入参
        List<CommonIteratorVO> commonIteratorVOList = (List<CommonIteratorVO>) point.getArgs()[0];
        log.info("入参数量: {}", commonIteratorVOList.size());
        CommonIteratorVO commonIteratorVO = commonIteratorVOList.get(0);

        Object proceed = point.proceed();
        // 业务处理
        this.logReturnResult(proceed,commonIteratorVO);
//        for (CommonIteratorVO commonIteratorVO : commonIteratorVOList) {
//            String typeDefName = commonIteratorVO.getTypeDefName();
//            if (typeDefName.indexOf("|")>=0){
//                typeDefName=typeDefName.split("|")[0];
//            }
//            if (typeDefName.equals("ty.inteplm.doc.CTyDoc")){
//                docRevisionService.modifyTheDocHistoryStatusToInvalid(commonIteratorVO.getId());
//            }else if (typeDefName.equals("ty.inteplm.cad.CTyCADDoc")){
//                docRevisionService.modifyTheCadDocHistoryStatusToInvalid(commonIteratorVO.getId());
//            }
//        }
        return proceed;
    }

    /**
     * 处理出参
     * @param result
     */
    private void logReturnResult(Object result,CommonIteratorVO commonIteratorVO) {
        if (result instanceof ResponseResult) {
            ResponseResult<List<BusinessObjectVO>> response = (ResponseResult<List<BusinessObjectVO>>) result;
            log.info("接口返回 - 状态码: {}, 返回体: {}",
                     response.getCode(), response.getData());
            List<BusinessObjectVO> data = response.getData();
            this.creatStatusinfo(data.get(0),commonIteratorVO);
        } else {
            log.info("接口返回: {}", result);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void creatStatusinfo(BusinessObjectVO businessObjectVO,CommonIteratorVO commonIteratorVO) {
        //根据需求状态表编码查询
        RtCfgStatusDTO dto = new RtCfgStatusDTO();
        dto.setOid(commonIteratorVO.getId());//上个版本的oid
        RtCfgStatusInfoDO rtCfgStatusInfoDO = rtCfgStatusInfoMapper.selectByStatusCode(dto);
        if (ObjectUtil.isNotEmpty(rtCfgStatusInfoDO)) {
            // 获取明细数据
            List<RtCfgStatusInfodetailDO> rtCfgStatusInfodetailDOS = rtCfgStatusInfoMapper.selectdetailByStatusId(rtCfgStatusInfoDO.getStatusid());

            // 生成新的状态ID
            String newStatusId = String.valueOf(snowflakeIdComponent.getInstance().nextId());

            // 更新主表数据  建议更新时间和 变更原因 变更来源
            rtCfgStatusInfoDO.setStatusid(newStatusId);
            rtCfgStatusInfoDO.setOid(businessObjectVO.getId());//修订后的版本oid
            rtCfgStatusInfoDO.setFCreatedate(new Date());
            rtCfgStatusInfoDO.setFcreateusername(TyAccountContext.getUser().getName());
            rtCfgStatusInfoDO.setLastVersionOid(new BigInteger(commonIteratorVO.getId()));
            rtCfgStatusInfoDO.setFDeletemark(0);
            rtCfgStatusInfoDO.setFEnabledmark(1);
            rtCfgStatusInfoDO.setFDescription("由"+rtCfgStatusInfoDO.getStatustitle()+"修订而来");
            Long insertResult = rtCfgStatusInfoMapper.insertByRtCfgStatusInfo(rtCfgStatusInfoDO);

            // 插入明细数据
            if (insertResult > 0 && rtCfgStatusInfodetailDOS != null && !rtCfgStatusInfodetailDOS.isEmpty()) {
                List<RtCfgStatusInfodetailDO> detailList = new ArrayList<>();
                for (RtCfgStatusInfodetailDO detail : rtCfgStatusInfodetailDOS) {
                    RtCfgStatusInfodetailDO newDetail = new RtCfgStatusInfodetailDO();
                    BeanUtil.copyProperties(detail,newDetail);
                    newDetail.setDid(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
                    newDetail.setInfoid(newStatusId);
                    newDetail.setFCreateusername(TyAccountContext.getUser().getName());
                    newDetail.setFCreatedate(new Date());
                    newDetail.setFDeletemark(0);
                    newDetail.setFEnabledmark(1);
//                    newDetail.setFDescription("由"+rtCfgStatusInfoDO.getStatustitle()+"修订而来");
                    detailList.add(newDetail);
                }
                rtCfgStatusInfodetailMapper.batchInsertRtCfgStatusInfodetail(detailList); // 使用批量插入优化性能
            }
        }
    }

}
